<?php


namespace App\Models;


use App\Services\AlipayService;
use App\Services\ZlbService;
use Illuminate\Database\Eloquent\Model;

class ZlbInsurance extends Model
{
    protected $table = "order_insurance";
    protected $primaryKey = 'id';
    public $timestamps = false;

    const STATUS_FAIL = 0;//失败
    const STATUS_SUCCESS = 1;//投保成功
    const STATUS_DISCHARGE = 2;//退保
        const STATUS_LIST = [
        self::STATUS_FAIL => '失败',
        self::STATUS_SUCCESS => '投保成功',
        self::STATUS_DISCHARGE => '退保',
    ];

    /**
     * 保单上传oss
     * @param $data
     * @return array
     */
    public static function setOss($data){
        $file = file_get_contents($data['policyUrl']);
        $fileName = $data['policyNo'].".pdf";
        $path = (dirname(dirname(dirname(__FILE__)))) . '/storage/tmp/'.$fileName;
        file_put_contents($path,$file);
        $res = AlipayService::upload($fileName,$path);
        return $res;
    }

    /**
     * 创建保单添加数据
     * @param $tradeNo
     * @param $result
     */
    public static function insuranceAdd($tradeNo,$result,$seller_id){
         if(isset($result['result_msg']) && $result['result_msg'] == 'success' && $result['code'] == 0 && $result['result_code'] == 200 && isset($result['response_data'])){
             //成功
             ZlbService::requestLog('租赁宝投保成功',[$tradeNo],$result);
             $data = json_decode($result['response_data'],true);
             $urlPath = self::setOss($data);
             $urlPath = isset($urlPath['data']) ? $urlPath['data']: '';
             $responseData = [
                 'policy_price'=>toYuanBYFen($data['premium']),
                 'policy_no'=>$data['policyNo'],
                 'policy_url'=>$data['policyUrl'],
                 'policy_path'=>$urlPath,
                 'start_time'=>$data['insuranceStartTime'],
                 'end_time'=>$data['insuranceEndTime'],
                 'status'=>self::STATUS_SUCCESS,
                 'account_balance'=>isset($data['accountBalance']) ? toYuanBYFen($data['accountBalance']) : 0,
                 'buy_result'=>json_encode($result),
                 'tx_hash'=>$data['txHash'],
                 'create_time'=>$data['insureDate'],
             ];
             //扣除商户账户金额
             $com = $data['leaseInsuredInfoResponse']['insuredName'];//商户公司名称
            //  if($com != '广州皓海同舟信息技术有限公司'){
             if($seller_id != 1653450768){
                 //查询商户ID和余额
                //  $shop_user = ShopUser::where("mechanism",$com)->select('member_id','shop_balance')->first();
                 $shop_user = ShopUser::where("member_id",$seller_id)->select('member_id','shop_balance')->first();
                 $shop_user = obToArray($shop_user);
                //非自营扣除金额
                 $premium = toYuanBYFen($data['premium']);//保费
                 if($shop_user){
                     $trans = [
                        'member_id'=>$shop_user['member_id'],
                        'amount'=>'-'.$premium,//保费
                        'before_balance'=>$shop_user['shop_balance'],
                        'after_balance'=>$shop_user['shop_balance'] - $premium,
                        'trans_type'=>ShopTrans::ORDER_TRANS_TYPE_INSURANCE,
                        'create_time'=>dateFormat(time()),
                        'remarks'=>'购买保险',
                    ];
                    ShopTrans::insert($trans);
                    ShopUser::where(array('member_id' => $shop_user['member_id']))->decrement('shop_balance', $premium); //减
                 }else{
                     $trans = [
                        'amount'=>'-'.$premium,//保费
                        'trans_type'=>ShopTrans::ORDER_TRANS_TYPE_INSURANCE,
                        'create_time'=>dateFormat(time()),
                        'remarks'=>'未知商户购买保险',
                    ];
                    ShopTrans::insert($trans);
                 }
             }
             
             $res = obToArray(ZlbInsurance::where(['order_no'=>$tradeNo])->first());
             if($res){
                 ZlbInsurance::where(['order_no'=>$tradeNo])->update($responseData);
             }else{
                 $responseData['order_no'] = $tradeNo;
                 ZlbInsurance::insertGetId($responseData);
             }
         }else{
             //失败
             $fail_data = [
                 'status'=>self::STATUS_FAIL,
                 'create_time'=>dateFormat(time()),
                 'buy_result'=>json_encode($result),
             ];
             $res = obToArray(ZlbInsurance::where(['order_no'=>$tradeNo])->first());
             if($res){
                 ZlbInsurance::where(['order_no'=>$tradeNo])->update($fail_data);
             }else{
                 $fail_data['order_no'] = $tradeNo;
                 ZlbInsurance::insertGetId($fail_data);
             }
             ZlbService::requestLog('租赁宝投保失败',[$tradeNo],$result);
         }
    }

    /**
     * 退保添加数据
     * @param $tradeNo
     * @param $result
     */
    public static function insuranceRefundAdd($tradeNo,$result){
        if(
            isset($result['result_msg']) &&
            $result['result_msg'] == 'success'
            && $result['code'] == 0 &&
            $result['result_code'] == 200
            && isset($result['response_data']) &&
            $result['response_data']['status'] == 'CACEL_SUCCESS'
        ){
            //成功
            ZlbService::requestLog('租赁宝退保成功',[$tradeNo],$result);
            $data = $result['response_data'];
            $responseData = [
                'refund_time'=>dateFormat(time()),
                'status'=>self::STATUS_DISCHARGE,
                'discharge_price'=>isset($data['backAmount']) ? $data['backAmount'] : '',
                'refund_result'=>json_encode($result),
                'refund_tx_hash'=>isset($data['backTxHash']) ? $data['backTxHash'] : '',
                'refund_number'=>isset($data['backInsuranceNumber']) ? $data['backInsuranceNumber'] : '',
            ];
            ZlbInsurance::where(['order_no'])->update($responseData);
        }else{
            //失败
            ZlbService::requestLog('租赁宝退保失败',[$tradeNo],$result);
        }
    }


}
